import 'dart:math';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:home_framework/models/dynamic_entity.dart';
import 'package:home_framework/view_models/dynamic/dynamic_detail_model.dart';
import 'package:home_framework/view_models/dynamic/dynamic_model.dart';
import 'package:provider/provider.dart';

class DynamicDetailWrapper extends StatelessWidget {
  final String id;
  const DynamicDetailWrapper({Key? key, required this.id}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<DynamicDetailModel>(
        create: (context) => DynamicDetailModel(),
        child: Stack(
          children: [
            _DynamicDetailPage(id),
            Positioned(
                bottom: 0,
                height: 60,
                width: MediaQuery.of(context).size.width,
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: [
                    _PraiseButton(),
                    _FavorButton(),
                  ],
                ))
          ],
        ));
  }
}

class _FavorButton extends StatelessWidget {
  const _FavorButton({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    print('FavorButton');
    return Container(
      alignment: Alignment.center,
      color: Colors.green[400],
      child: TextButton(
        onPressed: () {
          context.read<DynamicDetailModel>().updateFavorCount();
        },
        child: Text(
          context.select<DynamicDetailModel, String>(
            (DynamicDetailModel dyanmicDetail) {
              return '收藏 ' + dyanmicDetail.favorCount.toString();
            },
          ),
          style: TextStyle(color: Colors.white),
        ),
        style: ButtonStyle(
            minimumSize: MaterialStateProperty.resolveWith(
                (states) => Size((MediaQuery.of(context).size.width / 2), 60))),
      ),
    );
  }
}

class _PraiseButton extends StatelessWidget {
  const _PraiseButton({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    print('PraiseButton');
    return Container(
      alignment: Alignment.center,
      color: Colors.blue,
      child: TextButton(
        onPressed: () {
          context.read<DynamicDetailModel>().updatePraiseCount();
        },
        child: Text(
          context.select<DynamicDetailModel, String>(
            (DynamicDetailModel dyanmicDetail) {
              return '点赞 ' + dyanmicDetail.praiseCount.toString();
            },
          ),
          style: TextStyle(color: Colors.white),
        ),
        style: ButtonStyle(
            minimumSize: MaterialStateProperty.resolveWith((states) =>
                Size((MediaQuery.of(context).size.width / 2 - 1), 60))),
      ),
    );
  }
}

class _DynamicDetailPage extends StatefulWidget {
  final String id;
  _DynamicDetailPage(this.id, {Key? key}) : super(key: key);

  _DynamicDetailState createState() => _DynamicDetailState();
}

class _DynamicDetailState extends State<_DynamicDetailPage> {
  @override
  void initState() {
    super.initState();
    context.read<DynamicDetailModel>().getDynamic(widget.id).then((success) {
      if (success) {
        context.read<DynamicDetailModel>().updateViewCount().then((success) {
          if (success) {
            context
                .read<DynamicModel>()
                .update(context.read<DynamicDetailModel>().currentDynamic!);
          }
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    print('_DynamicDetailPage');
    DynamicEntity? currentDynamic =
        context.select<DynamicDetailModel, DynamicEntity?>(
      (dynamicDetail) => dynamicDetail.currentDynamic,
    );
    return Scaffold(
      appBar: AppBar(
        title: Text('动态详情'),
        brightness: Brightness.dark,
      ),
      body: currentDynamic == null
          ? Center(
              child: Text('请稍候...'),
            )
          : _getDetailWidget(currentDynamic),
    );
  }

  Widget _getDetailWidget(DynamicEntity currentDynamic) {
    return CustomScrollView(
      slivers: [
        SliverToBoxAdapter(
          child: Container(
            margin: EdgeInsets.fromLTRB(10, 10, 10, 5),
            child: Text(
              currentDynamic.title,
              style: TextStyle(
                fontSize: 16.0,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
        ),
        _viewCountWrapper(
          context
              .read<DynamicDetailModel>()
              .currentDynamic!
              .viewCount
              .toString(),
        ),
        SliverToBoxAdapter(
          child: CachedNetworkImage(
            imageUrl: currentDynamic.imageUrl,
            height: 200,
            fit: BoxFit.fill,
          ),
        ),
        SliverToBoxAdapter(
          child: Container(
            margin: EdgeInsets.all(10),
            child: Text(
              currentDynamic.content,
              style: TextStyle(
                fontSize: 14.0,
              ),
            ),
          ),
        ),
      ],
    );
  }

  SliverToBoxAdapter _viewCountWrapper(String text) {
    return SliverToBoxAdapter(
      child: Container(
        margin: EdgeInsets.fromLTRB(10, 0, 10, 10),
        height: 20,
        child: Row(children: [
          Icon(
            Icons.remove_red_eye_outlined,
            size: 14.0,
            color: Colors.grey,
          ),
          SizedBox(width: 5),
          Text(
            text,
            style: TextStyle(color: Colors.grey, fontSize: 14.0),
          ),
        ]),
      ),
    );
  }
}
